package com.jingming.consult.videoplayer;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.CountDownTimer;
import android.text.Html;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jingming.consult.R;
import com.jingming.consult.utils.DisplayUtil;
import com.jingming.consult.utils.NetworkUtils;
import com.jingming.consult.utils.SharepreferencesUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * 仿腾讯视频热点列表页播放器控制器.
 */
public class TxVideoPlayerController
        extends NiceVideoPlayerController
        implements View.OnClickListener,
        ChangeClarityDialog.OnClarityChangedListener, SeekBar.OnSeekBarChangeListener {
    private Context mContext;
    private FrameLayout mCenterStart;
    private ImageView mImage;
    private ImageView getmImageCenterStar;
    private RelativeLayout mTop;
    private RelativeLayout mBack;
    private TextView mTitle;
    private boolean isList = false;

    private LinearLayout mBottom;
    private TextView mPosition;
    private TextView mDuration;
    private SeekBar mSeek, gone_progress;

    private ImageView mFullScreen;
    private TextView tv_mobile_network_hint;

    private RelativeLayout rlPraent;
    private LinearLayout mLoading;
    private TextView mLoadText;
    private LinearLayout mChangePositon;
    private TextView mChangePositionCurrent;
    private ProgressBar mChangePositionProgress;
    private LinearLayout mChangeBrightness;
    private ProgressBar mChangeBrightnessProgress;
    private LinearLayout mChangeVolume;
    private ProgressBar mChangeVolumeProgress;
    private LinearLayout mError;
    private TextView mRetry;
    private LinearLayout mCompleted;
    private TextView mReplay;
    private RelativeLayout mShare;
    private boolean topBottomVisible;
    private CountDownTimer mDismissTopBottomCountDownTimer;
    private List<Clarity> clarities;
    private int defaultClarityIndex;
    private FrameLayout fmextend;//视频播放器扩展view
    private ImageView gesture_iv_progress;//快进还是快退
    private RelativeLayout rl_ad_center;
    private RelativeLayout rl_ad_right;
    private ImageView iv_ad_close_center;
    private ImageView iv_ad_close_right;
    private ImageView iv_bottom_play;
    private FrameLayout guangGaoPlayer;
    long millisUntilFinished = 0;
    private LinearLayout rl_nowifi;
    private TextView tv_nowifi;
    private TextView tv_ad_center;
    private boolean isFullScreen = false;
    private int longTime = 0;
    private RecyclerView list_change;
    private LiveChangeAdapter adapter;
    private List<CollegeGetShfeUrlBean.Urls> changes = new ArrayList<>();
    private TextView tv_change;
    private LinearLayout ll_live_change;
    private TextView tv_live_mode;
    private int changeType;

    private class MyRunnable implements Runnable {
        @Override
        public void run() {
            longTime = longTime + 1000;
        }
    }

    public TxVideoPlayerController(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public TxVideoPlayerController(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }

    public TxVideoPlayerController(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    public FrameLayout getFmextend() {
        return fmextend;
    }

    public View getmCenterStart() {
        return mCenterStart;
    }

    /**
     * 是否在列表播放
     *
     * @param list 列表不显示 返回和分享按钮
     */
    public void setList(boolean list) {
        isList = list;
        if (!isList) {
            mShare.setVisibility(VISIBLE);
            mBack.setVisibility(VISIBLE);
        } else {
            mShare.setVisibility(GONE);
            mBack.setVisibility(GONE);
        }
    }


    private void init() {

        LayoutInflater.from(mContext).inflate(R.layout.tx_video_palyer_controller, this, true);
        rlPraent = findViewById(R.id.rlPraent);
        rlPraent.setOnClickListener(this);
        fmextend = findViewById(R.id.fmextend);
        tv_mobile_network_hint = findViewById(R.id.tv_mobile_network_hint);
        gone_progress = findViewById(R.id.gone_progress);
        mCenterStart = findViewById(R.id.center_start);
        getmImageCenterStar = new ImageView(getContext());
        getmImageCenterStar.setImageResource(R.mipmap.icon_1zx_sp_52play);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT,
                Gravity.CENTER);
        mCenterStart.addView(getmImageCenterStar, 0, params);
        mImage = findViewById(R.id.image);

        mImage = findViewById(R.id.image);

        mTop = findViewById(R.id.top);
        mBack = findViewById(R.id.back);
        mTitle = findViewById(R.id.title);

        mBottom = findViewById(R.id.bottom);
        mPosition = findViewById(R.id.position);
        mDuration = findViewById(R.id.duration);
        mSeek = findViewById(R.id.seek);
        mFullScreen = findViewById(R.id.full_screen);
//        mClarity = (TextView) findViewById(R.id.clarity);

        mLoading = findViewById(R.id.loading);
        mLoadText = findViewById(R.id.load_text);

        mChangePositon = findViewById(R.id.change_position);
        mChangePositionCurrent = findViewById(R.id.change_position_current);
        mChangePositionProgress = findViewById(R.id.change_position_progress);

        mChangeBrightness = findViewById(R.id.change_brightness);
        mChangeBrightnessProgress = findViewById(R.id.change_brightness_progress);

        mChangeVolume = findViewById(R.id.change_volume);
        mChangeVolumeProgress = findViewById(R.id.change_volume_progress);

        mError = findViewById(R.id.error);
        mRetry = findViewById(R.id.retry);

        mCompleted = findViewById(R.id.completed);
        mReplay = findViewById(R.id.replay);
        mShare = findViewById(R.id.share);
        gesture_iv_progress = findViewById(R.id.gesture_iv_progress);
        guangGaoPlayer = findViewById(R.id.guangGaoPlayer);
        guangGaoPlayer.setOnClickListener(this);
        //视频播放器
        FrameLayout fyVideoPlayer = findViewById(R.id.fyVideoPlayer);
        if (mNiceVideoPlayer == null) {
            mNiceVideoPlayer = new NiceVideoPlayer(getContext());
            FrameLayout.LayoutParams videoPlayerParams = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            fyVideoPlayer.addView((View) mNiceVideoPlayer, videoPlayerParams);
            mNiceVideoPlayer.setController(this);
        }
        mBack.setOnClickListener(this);
        mCenterStart.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mFullScreen.setOnClickListener(this);
        mRetry.setOnClickListener(this);
        mShare.setOnClickListener(this);
        mReplay.setOnClickListener(this);
        mSeek.setOnSeekBarChangeListener(this);


        rl_ad_center = findViewById(R.id.rl_ad_center);
        rl_ad_center.setOnClickListener(this);
        rl_ad_right = findViewById(R.id.rl_ad_right);
        rl_ad_right.setOnClickListener(this);

        iv_ad_close_center = findViewById(R.id.iv_ad_close_center);
        iv_ad_close_center.setOnClickListener(this);
        tv_ad_center = findViewById(R.id.tv_ad_center);
        iv_ad_close_right = findViewById(R.id.iv_ad_close_right);
        iv_ad_close_right.setOnClickListener(this);
        iv_bottom_play = findViewById(R.id.iv_bottom_play);
        iv_bottom_play.setOnClickListener(this);
        rl_nowifi = findViewById(R.id.rl_nowifi);
        tv_nowifi = findViewById(R.id.tv_nowifi);
        tv_nowifi.setOnClickListener(this);

        list_change = findViewById(R.id.list_change);
        list_change.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new LiveChangeAdapter(getContext(), changes);
        list_change.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mNiceVideoPlayer.releasePlayer();
                list_change.setVisibility(View.GONE);
                tv_change.setVisibility(View.GONE);
                for (int i = 0; i < changes.size(); i++) {
                    CollegeGetShfeUrlBean.Urls data = changes.get(i);
                    if (i == position) {
                        data.setSelected(true);
                        switch (changes.get(i).getType()) {
                            case "ud":
                                tv_change.setText("超清");
                                changeType = 1;
                                break;
                            case "hd":
                                tv_change.setText("高清");
                                changeType = 2;
                                break;
                            case "sd":
                                tv_change.setText("标清");
                                changeType = 3;
                                break;
                            case "ld":
                                tv_change.setText("流畅");
                                changeType = 4;
                                break;
                        }
                        tv_live_mode.setText("请切换流畅模式");
                    } else {
                        data.setSelected(false);
                    }
                    changes.set(i, data);
                }

                adapter.notifyDataSetChanged();

            }
        });
        tv_change = findViewById(R.id.tv_change);
        tv_change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (list_change.getVisibility() == View.GONE) {
                    list_change.setVisibility(View.VISIBLE);
                } else if (list_change.getVisibility() == View.VISIBLE) {
                    list_change.setVisibility(View.GONE);
                }
            }
        });
        ll_live_change = findViewById(R.id.ll_live_change);
        ll_live_change.setOnClickListener(new View.OnClickListener() {
            private int position1;
            private int position2;
            private CollegeGetShfeUrlBean.Urls data1;
            private CollegeGetShfeUrlBean.Urls data2;

            @Override
            public void onClick(View v) {
                for (int i = 0; i < changes.size(); i++) {
                    if (changes.get(i).isSelected()) {
                        position2 = i;
                        data2 = changes.get(i);
                        if (i < changes.size() - 1) {
                            position1 = i;
                            data1 = changes.get(i + 1);
                        }
                    }
                }
                ll_live_change.setVisibility(View.GONE);
                mNiceVideoPlayer.releasePlayer();
                tv_change.setText(data1.getName());
                switch (data1.getName()) {
                    case "超清":
                        changeType = 1;
                        break;
                    case "高清":
                        changeType = 2;
                        break;
                    case "标清":
                        changeType = 3;
                        break;
                    case "流畅":
                        changeType = 4;
                        break;
                }
                data1.setSelected(true);
                changes.set(position1, data1);

                data2.setSelected(false);
                changes.set(position2, data2);

                adapter.notifyDataSetChanged();
            }
        });
        RelativeLayout rl_live_change_close = findViewById(R.id.rl_live_change_close);
        rl_live_change_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_live_change.setVisibility(View.GONE);
            }
        });
        tv_live_mode = findViewById(R.id.tv_live_mode);

    }

    @Override
    public void setTitle(String title) {
        mTitle.setText(Html.fromHtml(title));
    }


    /**
     * @return 封面图
     */
    @Override
    public ImageView imageView() {
        return mImage;
    }

    @Override
    public void setImage(@DrawableRes int resId) {
        mImage.setImageResource(resId);
    }

    @Override
    public void setNiceVideoPlayer(INiceVideoPlayer niceVideoPlayer) {
        super.setNiceVideoPlayer(niceVideoPlayer);
        // 给播放器配置视频链接地址
        if (clarities != null && clarities.size() > 0) {
            mNiceVideoPlayer.setUp(clarities.get(defaultClarityIndex).videoUrl);
        }
    }

    @Override
    public void setNiceVideoPlayer1(INiceVideoPlayer niceVideoPlayer1) {
        super.setNiceVideoPlayer1(niceVideoPlayer1);
        // 给播放器配置视频链接地址
        if (clarities != null && clarities.size() > 0) {
            mNiceVideoPlayer1.setUp(clarities.get(defaultClarityIndex).videoUrl);
        }
    }

    @Override
    public void release() {
        super.release();
    }

    /**
     * 判断是否显示网络变换提示
     */
    public void setNetworkHint() {
        //判断是否本地网络显示提示框
        if (!isWifi(mContext)) {
            if (tv_mobile_network_hint != null) {
                tv_mobile_network_hint.setVisibility(View.VISIBLE);
                rlPraent.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        tv_mobile_network_hint.setVisibility(View.GONE);
                    }
                }, 3000);  //3000毫秒后执行
            }
        }
    }

    /**
     * @param mContext 上下文
     * @return false 不是wifi  true wifi连接
     */
    private static boolean isWifi(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI;
    }

    /**
     * 设置清晰度
     *
     * @param clarities 清晰度及链接
     */
    public void setClarity(List<Clarity> clarities, int defaultClarityIndex) {
        if (clarities != null && clarities.size() > 0) {
            this.clarities = clarities;
            this.defaultClarityIndex = defaultClarityIndex;

            List<String> clarityGrades = new ArrayList<>();
            for (Clarity clarity : clarities) {
                clarityGrades.add(clarity.grade + " " + clarity.p);
            }
            // 初始化切换清晰度对话框
            ChangeClarityDialog mClarityDialog = new ChangeClarityDialog(mContext);
            mClarityDialog.setClarityGrade(clarityGrades, defaultClarityIndex);
            mClarityDialog.setOnClarityCheckedListener(this);
            // 给播放器配置视频链接地址
            if (mNiceVideoPlayer != null) {
                mNiceVideoPlayer.setUp(clarities.get(defaultClarityIndex).videoUrl);
            }
        }
    }

    @Override
    protected void onPlayStateChanged(int playState) {
        if (videoStateChange != null) {
            videoStateChange.videoStateChange(playState);
        }
        switch (playState) {
            case NiceVideoPlayer.STATE_IDLE:
                if (tempPlayNumText != null) {
                    tempPlayNumText.setVisibility(VISIBLE);
                }
                if (tempVipFlagImage != null) {
                    tempVipFlagImage.setVisibility(VISIBLE);
                }
                break;
            case NiceVideoPlayer.STATE_PREPARING:
                if (tempPlayNumText != null) {
                    tempPlayNumText.setVisibility(GONE);
                }
                if (tempVipFlagImage != null) {
                    tempVipFlagImage.setVisibility(GONE);
                }
                mLoading.setVisibility(View.VISIBLE);
                if (!isList) {
                    mShare.setVisibility(VISIBLE);
                    mBack.setVisibility(VISIBLE);
                }
                mLoadText.setText("正在准备...");
                mError.setVisibility(View.GONE);
                mCompleted.setVisibility(View.GONE);
                mBottom.setVisibility(View.GONE);
                mCenterStart.setVisibility(View.GONE);
                break;
            case NiceVideoPlayer.STATE_PREPARED:
                if (tempPlayNumText != null) {
                    tempPlayNumText.setVisibility(GONE);
                }
                if (tempVipFlagImage != null) {
                    tempVipFlagImage.setVisibility(GONE);
                }
                if (mNiceVideoPlayer1 != null) {
                    if (mNiceVideoPlayer1.isPrepared()) {
                        mTop.setVisibility(View.GONE);
                        mBottom.setVisibility(View.VISIBLE);
                        mFullScreen.setVisibility(View.VISIBLE);
                        iv_bottom_play.setVisibility(View.INVISIBLE);
                        mPosition.setVisibility(View.INVISIBLE);
                        mDuration.setVisibility(View.INVISIBLE);
                        mSeek.setVisibility(View.INVISIBLE);
                    }
                }
                if (mNiceVideoPlayer.isPrepared()) {
                    iv_bottom_play.setVisibility(View.VISIBLE);
                    mFullScreen.setVisibility(View.VISIBLE);
                    if (isFullScreen) {
                        mFullScreen.setVisibility(View.GONE);
                    }
                    mPosition.setVisibility(View.VISIBLE);
                    mDuration.setVisibility(View.VISIBLE);
                    mSeek.setVisibility(View.VISIBLE);
                }
                startUpdateProgressTimer();
                break;
            case NiceVideoPlayer.STATE_PLAYING:
                if (tempPlayNumText != null) {
                    tempPlayNumText.setVisibility(GONE);
                }
                if (tempVipFlagImage != null) {
                    tempVipFlagImage.setVisibility(GONE);
                }
                rl_ad_center.setVisibility(View.GONE);
                mError.setVisibility(GONE);
                mImage.setVisibility(View.GONE);
                mLoading.setVisibility(View.GONE);
                getmImageCenterStar.setImageResource(R.mipmap.icon_1zx_sp_52stop);
                iv_bottom_play.setImageResource(R.mipmap.icon_wzxq_zhanting);
                startDismissTopBottomTimer();
                break;
            case NiceVideoPlayer.STATE_PAUSED:
                if (tempPlayNumText != null) {
                    tempPlayNumText.setVisibility(GONE);
                }
                if (tempVipFlagImage != null) {
                    tempVipFlagImage.setVisibility(GONE);
                }
                mLoading.setVisibility(View.GONE);
                getmImageCenterStar.setImageResource(R.mipmap.icon_1zx_sp_52play);
                iv_bottom_play.setImageResource(R.mipmap.icon_wzxq_bofang);
                cancelDismissTopBottomTimer();
                break;
            case NiceVideoPlayer.STATE_BUFFERING_PLAYING:
                if (tempPlayNumText != null) {
                    tempPlayNumText.setVisibility(GONE);
                }
                if (tempVipFlagImage != null) {
                    tempVipFlagImage.setVisibility(GONE);
                }
                mLoading.setVisibility(View.VISIBLE);
                getmImageCenterStar.setImageResource(R.mipmap.icon_1zx_sp_52stop);
                iv_bottom_play.setImageResource(R.mipmap.icon_wzxq_zhanting);
                mLoadText.setText("正在缓冲...");
                if (!isList) {
                    mShare.setVisibility(VISIBLE);
                    mBack.setVisibility(VISIBLE);
                }
                startDismissTopBottomTimer();
                break;
            case NiceVideoPlayer.STATE_BUFFERING_PAUSED:
                if (tempPlayNumText != null) {
                    tempPlayNumText.setVisibility(GONE);
                }
                if (tempVipFlagImage != null) {
                    tempVipFlagImage.setVisibility(GONE);
                }
                mLoading.setVisibility(View.VISIBLE);
                getmImageCenterStar.setImageResource(R.mipmap.icon_1zx_sp_52play);
                iv_bottom_play.setImageResource(R.mipmap.icon_wzxq_bofang);
                mLoadText.setText("正在缓冲...");
                cancelDismissTopBottomTimer();
                break;
            case NiceVideoPlayer.STATE_ERROR:
                if (mNiceVideoPlayer1 != null && mNiceVideoPlayer1.isError()) {
                    guangGaoPlayer.setVisibility(View.GONE);
                    mNiceVideoPlayer1.release();
                    mNiceVideoPlayer1 = null;
                    if (mNiceVideoPlayer != null) {
                        mNiceVideoPlayer.start();
                    }
                    return;
                }
                if (tempPlayNumText != null) {
                    tempPlayNumText.setVisibility(VISIBLE);
                }
                if (tempVipFlagImage != null) {
                    tempVipFlagImage.setVisibility(GONE);
                }
                cancelUpdateProgressTimer();
                setTopBottomVisible(false);
                mTop.setVisibility(View.VISIBLE);
                mError.setVisibility(View.VISIBLE);
                if (!NetworkUtils.isNetworkAvailable()) {
                    mError.setVisibility(View.VISIBLE);
                }
                if (!isList) {
                    mShare.setVisibility(VISIBLE);
                    mBack.setVisibility(VISIBLE);
                }
            case NiceVideoPlayer.STATE_COMPLETED:
                if (tempPlayNumText != null) {
                    tempPlayNumText.setVisibility(VISIBLE);
                }
                if (tempVipFlagImage != null) {
                    tempVipFlagImage.setVisibility(GONE);
                }
                cancelUpdateProgressTimer();
                setTopBottomVisible(false);
                mImage.setVisibility(View.VISIBLE);
                mCompleted.setVisibility(View.VISIBLE);
                release();
                break;
        }
    }


    @Override
    protected void onPlayModeChanged(int playMode) {
        if (videoModeChange != null) {
            videoModeChange.videoModeChange(playMode);
        }
        switch (playMode) {
            case NiceVideoPlayer.MODE_NORMAL:
                if (!isList) {
                    mShare.setVisibility(VISIBLE);
                }
                mFullScreen.setImageResource(R.mipmap.icon_wzxq_qp);
                mFullScreen.setVisibility(View.VISIBLE);
                mTitle.setVisibility(View.GONE);
                break;
            case NiceVideoPlayer.MODE_FULL_SCREEN:
                if (!isList) {
                    mShare.setVisibility(VISIBLE);
                    mBack.setVisibility(View.VISIBLE);
                }
           /*     mFullScreen.setVisibility(View.GONE);
                mFullScreen.setImageResource(R.drawable.xy_icon_tuichuquanping);*/
                mFullScreen.setImageResource(R.mipmap.icon_wzxq_tcqp);
                mTitle.setVisibility(View.VISIBLE);
                break;
            case NiceVideoPlayer.MODE_TINY_WINDOW://小窗模式
                if (!isList) {
                    mShare.setVisibility(VISIBLE);
                    mBack.setVisibility(View.GONE);
                }
                ViewGroup contentViewWindow = NiceUtil.scanForActivity(mContext)
                        .findViewById(android.R.id.content);
                // 小窗口的宽度为屏幕宽度的60%，长宽比默认为16:9，右边距、下边距为8dp。
                FrameLayout.LayoutParams paramsWindow = new FrameLayout.LayoutParams(
                        (int) (NiceUtil.getScreenWidth(mContext) * 0.6f),
                        (int) (NiceUtil.getScreenWidth(mContext) * 0.6f * 9f / 16f));
                paramsWindow.gravity = Gravity.BOTTOM | Gravity.END;
                paramsWindow.rightMargin = NiceUtil.dp2px(mContext, 8f);
                paramsWindow.bottomMargin = NiceUtil.dp2px(mContext, 8f);
                contentViewWindow.addView(rlPraent, paramsWindow);
                break;
        }
    }


    @Override
    protected void reset() {
        topBottomVisible = false;
        cancelUpdateProgressTimer();
        cancelDismissTopBottomTimer();
        mSeek.setProgress(0);
        gone_progress.setProgress(0);
        gone_progress.setSecondaryProgress(0);
        mSeek.setSecondaryProgress(0);
        getmImageCenterStar.setImageResource(R.mipmap.icon_1zx_sp_52play);
        mImage.setVisibility(View.VISIBLE);
        mBottom.setVisibility(View.VISIBLE);
        mPosition.setVisibility(View.GONE);
        mDuration.setVisibility(View.GONE);
        mSeek.setVisibility(View.GONE);
        mFullScreen.setVisibility(View.GONE);
        if (iv_bottom_play != null) {
            iv_bottom_play.setImageResource(R.mipmap.icon_wzxq_bofang);
        }
        if (isFullScreen) {
            mFullScreen.setImageResource(R.mipmap.icon_wzxq_tcqp);
        } else {
            mFullScreen.setImageResource(R.mipmap.icon_wzxq_qp);
        }
        mTop.setVisibility(View.VISIBLE);
        if (!isList) {
            mShare.setVisibility(VISIBLE);
            mBack.setVisibility(View.VISIBLE);
        }
        mLoading.setVisibility(View.GONE);
        mCompleted.setVisibility(View.GONE);
    }

    /**
     * 尽量不要在onClick中直接处理控件的隐藏、显示及各种UI逻辑。
     * UI相关的逻辑都尽量到{@link #onPlayStateChanged}和{@link #onPlayModeChanged}中处理.
     */
    private boolean isWifi = false;

    @Override
    public void onClick(View v) {
        if (v == mCenterStart) {
            isWifi = (boolean) SharepreferencesUtils.getParam("video_is_wifi", false);
            if (NetworkUtils.isWifiActive(mContext)) {
                if (TextUtils.isEmpty(mUrl) && controllerCallBack != null) {
                    //如果链接为空 重新获取
                    controllerCallBack.payGetUrl();
                    return;
                }
                if (controllerViewCallBack != null) {
                    controllerViewCallBack.onClickPlayButton(v);
                }
                if (mNiceVideoPlayer.isIdle()) {
                    mNiceVideoPlayer.start();
                } else {
                    if (mNiceVideoPlayer.isPlaying() || mNiceVideoPlayer.isBufferingPlaying()) {
                        mNiceVideoPlayer.pause();
                    } else if (mNiceVideoPlayer.isPaused() || mNiceVideoPlayer.isBufferingPaused()) {
                        mNiceVideoPlayer.restart();
                    }
                }
            } else {
                if (NetworkUtils.isNetworkAvailable()) {
                    if (!isWifi) {
                        showDialog();
                        return;
                    }
                    if (TextUtils.isEmpty(mUrl) && controllerCallBack != null) {
                        //如果链接为空 重新获取
                        controllerCallBack.payGetUrl();
                        return;
                    }
                    if (controllerViewCallBack != null) {
                        controllerViewCallBack.onClickPlayButton(v);
                    }
                    if (mNiceVideoPlayer.isIdle()) {
                        mNiceVideoPlayer.start();
                        //当音频和视频同时播放时，关闭音频
                    } else {
                        if (mNiceVideoPlayer.isPlaying() || mNiceVideoPlayer.isBufferingPlaying()) {
                            mNiceVideoPlayer.pause();
                        } else if (mNiceVideoPlayer.isPaused() || mNiceVideoPlayer.isBufferingPaused()) {
                            mNiceVideoPlayer.restart();
                        }
                    }
                } else {
                    Toast.makeText(mContext, "请检查是否连接网络", Toast.LENGTH_SHORT).show();
                }
            }

        } else if (v == mBack) {

            if (isFullScreen()) {
                exitFullScreen();
            } else if (isTinyWindow()) {
                exitTinyWindow();
            } else {
                if (controllerCallBack != null) {
                    controllerCallBack.finishActivity();

                }
            }
        } else if (v == mFullScreen) {
            if (mNiceVideoPlayer.isNormal() || mNiceVideoPlayer.isTinyWindow()) {
                enterFullScreen();
            } else if (mNiceVideoPlayer.isFullScreen()) {
                mBack.setVisibility(GONE);
                exitFullScreen();
            }
        } else if (v == mRetry) {
            if (mNiceVideoPlayer1 != null) {
                mNiceVideoPlayer1.restart();
            } else {
                mCenterStart.performClick();
            }
        } else if (v == mReplay) {
            mRetry.performClick();
        } else if (v == mShare) {
            if (controllerCallBack != null) {
                controllerCallBack.share();
            }
        } else if (v == rlPraent) {
            if (mNiceVideoPlayer.isPlaying()
                    || mNiceVideoPlayer.isPaused()
                    || mNiceVideoPlayer.isBufferingPlaying()
                    || mNiceVideoPlayer.isBufferingPaused()) {
                setTopBottomVisible(!topBottomVisible);
            }
        } else if (v == iv_ad_close_center) {
            rl_ad_center.setVisibility(View.GONE);
        } else if (v == iv_ad_close_right) {
            rl_ad_right.setVisibility(View.GONE);
        } else if (v == iv_bottom_play) {
            isWifi = (boolean) SharepreferencesUtils.getParam("video_is_wifi", false);
            if (NetworkUtils.isWifiActive(mContext)) {
                if (TextUtils.isEmpty(mUrl) && controllerCallBack != null) {
                    //如果链接为空 重新获取
                    controllerCallBack.payGetUrl();
                    return;
                }
                if (controllerViewCallBack != null) {
                    controllerViewCallBack.onClickPlayButton(v);
                }
                if (mNiceVideoPlayer.isIdle()) {
                    mNiceVideoPlayer.start();
                    rl_ad_center.setVisibility(View.GONE);
                    //当音频和视频同时播放时，关闭音频
                } else {
                    if (mNiceVideoPlayer.isPlaying() || mNiceVideoPlayer.isBufferingPlaying()) {
                        mNiceVideoPlayer.pause();
                    } else if (mNiceVideoPlayer.isPaused() || mNiceVideoPlayer.isBufferingPaused()) {
                        mNiceVideoPlayer.restart();
                        rl_ad_center.setVisibility(View.GONE);
                    }
                }
            } else {
                if (NetworkUtils.isNetworkAvailable()) {
                    if (!isWifi) {
                        showDialog();
                        return;
                    }
                    if (TextUtils.isEmpty(mUrl) && controllerCallBack != null) {
                        //如果链接为空 重新获取
                        controllerCallBack.payGetUrl();
                        return;
                    }
                    if (controllerViewCallBack != null) {
                        controllerViewCallBack.onClickPlayButton(v);
                    }
                    if (mNiceVideoPlayer.isIdle()) {
                        mNiceVideoPlayer.start();
                        rl_ad_center.setVisibility(View.GONE);
                        //当音频和视频同时播放时，关闭音频
                    } else {
                        if (mNiceVideoPlayer.isPlaying() || mNiceVideoPlayer.isBufferingPlaying()) {
                            mNiceVideoPlayer.pause();
                        } else if (mNiceVideoPlayer.isPaused() || mNiceVideoPlayer.isBufferingPaused()) {
                            mNiceVideoPlayer.restart();
                            rl_ad_center.setVisibility(View.GONE);
                        }
                    }
                } else {
                    Toast.makeText(mContext, "请检查是否连接网络", Toast.LENGTH_SHORT).show();
                }
            }
        } else if (v == tv_nowifi) {
            isWifi = true;
            SharepreferencesUtils.setParam("video_is_wifi", isWifi);
            if (mNiceVideoPlayer1 != null) {
                if (mNiceVideoPlayer1.isIdle()) {
                    mNiceVideoPlayer1.start();
                    rl_nowifi.setVisibility(View.GONE);
                    //当音频和视频同时播放时，关闭音频
                }
            } else {
                if (mNiceVideoPlayer != null) {
                    if (mNiceVideoPlayer.isIdle()) {
                        mCenterStart.performClick();
                        rl_nowifi.setVisibility(View.GONE);
                        //当音频和视频同时播放时，关闭音频
                    }
                }
            }
        }
    }

    //显示判断wifi和其他网络的dialog
    private void showDialog() {
        setNoWifiVisible(true);
    }

    @Override
    public void onClarityChanged(int clarityIndex) {
        // 根据切换后的清晰度索引值，设置对应的视频链接地址，并从当前播放位置接着播放
        Clarity clarity = clarities.get(clarityIndex);
        long currentPosition = mNiceVideoPlayer.getCurrentPosition();
        mNiceVideoPlayer.releasePlayer();
        mNiceVideoPlayer.setUp(clarity.videoUrl);
        mNiceVideoPlayer.start(currentPosition);
    }

    @Override
    public void onClarityNotChanged() {
        // 清晰度没有变化，对话框消失后，需要重新显示出top、bottom
        setTopBottomVisible(true);
    }

    /**
     * 设置top、bottom的显示和隐藏
     *
     * @param visible true显示，false隐藏.
     */
    private void setTopBottomVisible(boolean visible) {
        mTop.setVisibility(visible ? View.VISIBLE : View.GONE);


        if (!isList) {
            mBack.setVisibility(visible ? View.VISIBLE : View.GONE);
            mShare.setVisibility(visible ? View.VISIBLE : View.GONE);
        }

        mCenterStart.setVisibility(visible ? View.VISIBLE : View.GONE);
        mBottom.setVisibility(visible ? View.VISIBLE : View.GONE);
        gone_progress.setVisibility(visible ? GONE : VISIBLE);
        topBottomVisible = visible;
        if (visible) {
            if (!mNiceVideoPlayer.isPaused() && !mNiceVideoPlayer.isBufferingPaused()) {
                startDismissTopBottomTimer();
            }
        } else {
            cancelDismissTopBottomTimer();
        }
    }

    public void setNoWifiVisible(boolean visible) {
        if (visible) {
            rl_nowifi.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 开启top、bottom自动消失的timer
     */
    private void startDismissTopBottomTimer() {
        cancelDismissTopBottomTimer();
        if (mDismissTopBottomCountDownTimer == null) {
            mDismissTopBottomCountDownTimer = new CountDownTimer(8000, 8000) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    if (mNiceVideoPlayer1 != null) {
                        return;
                    }
                    setTopBottomVisible(false);
                }
            };
        }
        mDismissTopBottomCountDownTimer.start();
    }

    /**
     * 取消top、bottom自动消失的timer
     */
    private void cancelDismissTopBottomTimer() {
        if (mDismissTopBottomCountDownTimer != null) {
            mDismissTopBottomCountDownTimer.cancel();
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        cancelDismissTopBottomTimer();
        cancelUpdateProgressTimer();
        int position = (int) (mNiceVideoPlayer.getDuration() * seekBar.getProgress() / 100);
        mNiceVideoPlayer.seekTo(position);
        if (mNiceVideoPlayer.isBufferingPaused() || mNiceVideoPlayer.isPaused()) {
            mNiceVideoPlayer.restart();
        }
        mNiceVideoPlayer.seekTo(position);
        startUpdateProgressTimer();
        startDismissTopBottomTimer();
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void updateProgress() {
        long position = mNiceVideoPlayer.getCurrentPosition();
        long duration = mNiceVideoPlayer.getDuration();
        int bufferPercentage = mNiceVideoPlayer.getBufferPercentage();
        mSeek.setSecondaryProgress(bufferPercentage);
        int progress = (int) (100f * position / duration);
        gone_progress.setSecondaryProgress(bufferPercentage);
        mSeek.setProgress(progress);
        gone_progress.setProgress(progress);
        mPosition.setText(NiceUtil.formatTime(position));
        mDuration.setText(NiceUtil.formatTime(duration));
        if (mNiceVideoPlayer1 != null && mNiceVideoPlayer1.isPlaying()) {
            millisUntilFinished = (mNiceVideoPlayer1.getDuration() - mNiceVideoPlayer1.getCurrentPosition()) / 1000;
            if (millisUntilFinished == 0) {
                guangGaoPlayer.setVisibility(View.GONE);
                mNiceVideoPlayer1.release();
                mNiceVideoPlayer1 = null;
                //需要把進度找過來
                mNiceVideoPlayer.start();
            }
        }


    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void showChangePosition(long duration, int newPositionProgress, boolean isAdvance) {
        mCenterStart.setVisibility(GONE);
        mChangePositon.setVisibility(View.VISIBLE);
        long newPosition = (long) (duration * newPositionProgress / 100f);
        gesture_iv_progress.setImageResource(isAdvance ? R.mipmap.sp_icon_kuaijin : R.mipmap.sp_icon_kuaitui);
        mChangePositionCurrent.setText(NiceUtil.formatTime(newPosition) + "/" + NiceUtil.formatTime(duration));
        mChangePositionProgress.setProgress(newPositionProgress);
        mSeek.setProgress(newPositionProgress);
        gone_progress.setProgress(newPositionProgress);
        mPosition.setText(NiceUtil.formatTime(newPosition));
    }

    @Override
    protected void hideChangePosition() {
        mChangePositon.setVisibility(View.GONE);
        mCenterStart.setVisibility(GONE);
    }

    @Override
    protected void showChangeVolume(int newVolumeProgress) {
        mCenterStart.setVisibility(GONE);
        mChangeVolume.setVisibility(View.VISIBLE);
        mChangeVolumeProgress.setProgress(newVolumeProgress);
    }

    @Override
    protected void hideChangeVolume() {
        mChangeVolume.setVisibility(View.GONE);
    }

    @Override
    protected void showChangeBrightness(int newBrightnessProgress) {
        mCenterStart.setVisibility(GONE);
        mChangeBrightness.setVisibility(View.VISIBLE);
        mChangeBrightnessProgress.setProgress(newBrightnessProgress);
    }

    @Override
    protected void hideChangeBrightness() {
        mChangeBrightness.setVisibility(View.GONE);
    }

    @Override
    public void enterFullScreen() {
        isFullScreen = true;
        mNiceVideoPlayer.enterFullScreen();
        mBack.setVisibility(VISIBLE);
        //全屏播放
        ViewGroup contentViewFull = NiceUtil.scanForActivity(mContext)
                .findViewById(android.R.id.content);
        this.removeView(rlPraent);
        /*if (contentViewFull.getChildCount() > 0) {
            contentViewFull.removeView(rlPraent);
        }*/
        FrameLayout.LayoutParams paramsFull = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        contentViewFull.addView(rlPraent, paramsFull);

        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rl_ad_center.getLayoutParams();
        params.width = DisplayUtil.dip2px(mContext, 375);
        params.height = DisplayUtil.dip2px(mContext, 212);
        // 根据布局参数的设置，重新设置view（这里用了text view，当然其他的view也是通用的）的大小
        rl_ad_center.setLayoutParams(params);

        RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams) iv_ad_close_center.getLayoutParams();
        params1.width = DisplayUtil.dip2px(mContext, 30);
        params1.height = DisplayUtil.dip2px(mContext, 30);
        // 根据布局参数的设置，重新设置view（这里用了text view，当然其他的view也是通用的）的大小
        iv_ad_close_center.setLayoutParams(params1);

        tv_ad_center.setTextSize(14);

    }

    @Override
    public boolean exitFullScreen() {
        isFullScreen = false;
        if (!isFullScreen())
            return false;
        mNiceVideoPlayer.exitFullScreen();
        mBack.setVisibility(GONE);

        RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams) rl_ad_center.getLayoutParams();
        params1.width = DisplayUtil.dip2px(mContext, 210);
        params1.height = DisplayUtil.dip2px(mContext, 119);
        // 根据布局参数的设置，重新设置view（这里用了text view，当然其他的view也是通用的）的大小
        rl_ad_center.setLayoutParams(params1);

        RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) iv_ad_close_center.getLayoutParams();
        params2.width = DisplayUtil.dip2px(mContext, 20);
        params2.height = DisplayUtil.dip2px(mContext, 20);
        // 根据布局参数的设置，重新设置view（这里用了text view，当然其他的view也是通用的）的大小
        iv_ad_close_center.setLayoutParams(params2);

        tv_ad_center.setTextSize(10);

        rl_ad_right.setVisibility(View.GONE);
        //退出全屏操作
        ViewGroup contentView = NiceUtil.scanForActivity(mContext)
                .findViewById(android.R.id.content);
        contentView.removeView(rlPraent);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        this.addView(rlPraent, params);
        mTop.setVisibility(View.GONE);
        mShare.setVisibility(View.GONE);
        return true;
    }


    @Override
    public void enterTinyWindow() {
        if (isTinyWindow())
            return;
        mNiceVideoPlayer.enterTinyWindow();
    }

    @Override
    public boolean exitTinyWindow() {
        if (!isTinyWindow())
            return false;
        mNiceVideoPlayer.exitTinyWindow();
        ViewGroup contentView = NiceUtil.scanForActivity(mContext)
                .findViewById(android.R.id.content);
        contentView.removeView(rlPraent);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        this.addView(rlPraent, params);
        return true;
    }


    /**
     *
     */
    private ControllerCallBack controllerCallBack;

    /**
     * 视频播放器相关回调
     *
     * @param controllerCallBack UI交互
     */
    public void setControllerCallBack(ControllerCallBack controllerCallBack) {
        this.controllerCallBack = controllerCallBack;
    }


    public void setRestart() {
        rl_ad_center.setVisibility(View.GONE);
    }


    /**
     * 分享  获取视频Url 关闭当前Activity
     */
    public interface ControllerCallBack {
        //视频分享
        void share();

        /**
         * 如果视频链接为空，重新获取
         */
        void payGetUrl();

        /**
         * 关闭当前界面
         */
        void finishActivity();

    }

    private ControllerViewCallBack controllerViewCallBack;

    //开始播放
    public void setControllerViewCallBack(ControllerViewCallBack controllerViewCallBack) {
        this.controllerViewCallBack = controllerViewCallBack;
    }

    public interface ControllerViewCallBack {
        //点击播放
        void onClickPlayButton(View v);
    }

    //在播放控制器中控制视频播放量的textview是否显示隐藏
    private TextView tempPlayNumText;

    public void setTempPlayNumText(TextView tempPlayNumText) {
        this.tempPlayNumText = tempPlayNumText;
    }

    //在播放控制器中控制VIP的标识是否显示隐藏   播放未开始显示 其他条件隐藏
    private ImageView tempVipFlagImage;

    public void setTempVipFlagImage(ImageView tempVipFlagImage) {
        this.tempVipFlagImage = tempVipFlagImage;
    }

    /**
     * @param centerStartView 自定义视频中心播放  暂停view\
     */
    public void setCenterStartView(View centerStartView) {
        mCenterStart.removeView(getmImageCenterStar);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT,
                Gravity.CENTER);
        mCenterStart.addView(centerStartView, 0, params);
    }

    public VideoStateChange videoStateChange;

    public void setVideoStateChange(VideoStateChange videoStateChange) {
        this.videoStateChange = videoStateChange;
    }

    /**
     * 视频播放状态切换
     */
    public interface VideoStateChange {
        void videoStateChange(int state);
    }

    public VideoModeChange videoModeChange;

    public void setVideoModeChange(VideoModeChange videoModeChange) {
        this.videoModeChange = videoModeChange;
    }

    /**
     * 视频播放状态切换
     */
    public interface VideoModeChange {
        void videoModeChange(int mode);
    }
}
